var express = require('express');
var router = express.Router();
const alipaySdk = require('../model/model')
const AlipayFormData = require('alipay-sdk/lib/form').default;
var { userModel, tokenModel, tradeModel, positionModel, profitModel, goldHerstoryModel, recurringInvestmentModel, TransactionChoice, RealTimeRatio, HistoryFund, Quote, TodayQuoteModel, WeekQuoteModel, MonthQuoteModel, YearQuoteModel, ProductModel, AddressModel, OrderModel } = require('../model/model');
var jsonwebtoken = require("jsonwebtoken")
const { add_accessToken, delete_access } = require('../token');
const { ChatCompletion, setEnvVariable } = require('@baiducloud/qianfan');
const { main } = require("../token/cardId")
require('dotenv').config();
const axios =require('axios')
const { MongoClient } = require('mongodb');
const cron = require('node-cron')
// MongoDB 连接
const uri = "mongodb+srv://nikiisme321:t36T3Qp1aFjqTFPq@cluster0.k7soc.mongodb.net/el";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });







//--------------------------------聊天方面------------------------------------------

// 设置 API Key 和 Secret Key
setEnvVariable('QIANFAN_AK', 'g12qd7J3lnji5tnvyxKZFbUm');
setEnvVariable('QIANFAN_SK', 'cHbZIqR7rNOXyKFU8ZupsIDuOoHgGUbI');

const client1 = new ChatCompletion({ Endpoint: 'completions_pro' });

// 处理聊天请求的路由
router.post('/chat', async (req, res) => {
  console.time('chatRequest');  // 开始计时
  console.log(123);

  try {
    const { messages } = req.body;
    // console.log(messages);

    const resp = await client1.chat({ messages });
    console.log(resp);

    console.timeEnd('chatRequest');  // 结束计时并输出时间
    // res.json({ result: resp.result });
    res.send({
      result: resp.result
    })
  } catch (error) {
    console.error('Error in chat:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

//-----------------------------------金价方面--------------------------------------------
// 清空数据表
router.post('/clear_all', async (req, res) => {
  await HistoryFund.deleteMany()
  await Quote.deleteMany()
  await WeekQuoteModel.deleteMany()
  await MonthQuoteModel.deleteMany()
  res.send({
    code: 200,
    msg: 'success'
  })
})
// 清空HistoryFund、Quote
// router.post('/clear_two', async (req, res) => {
//   await HistoryFund.deleteMany()
//   await Quote.deleteMany()
//   res.send({
//     code: 200,
//     msg: 'success'
//   })
// })
// 获取所有数据
router.get('/get_all', async (req, res) => {
  // 获取历史记录，只获取price有值的数据
  let result = await HistoryFund.find({ price: { $gt: 0 } }).sort({ date: 1 });
  // 获取历史数据-2
  // let result = await TodayQuoteModel.find()
  // 获取实时数据
  let quote = await Quote.findOne()
  // 获取周数据
  let weekQuote = await WeekQuoteModel.find().sort({ q59: 1 })
  // 获取月数据
  let monthQuote = await MonthQuoteModel.find().sort({ q59: 1 })
  // 获取年数据
  let YearQuote = await YearQuoteModel.find().sort({ date: 1 })

  res.send({
    code: 200,
    data: {
      quote: quote,
      result: result,
      week: weekQuote,
      month: monthQuote,
      year: YearQuote
    }
  })
});
// 根据用前端传来的价格，从 Quote中计算可买的黄金的克数
router.get('/get_gram', async (req, res) => {
  try {
    let price = req.query.price;
    if (!price || isNaN(price) || price <= 0) {
      return res.status(400).send({ code: 400, message: "Invalid price parameter" });
    }
    // 查询当前黄金报价
    let result = await Quote.findOne();
    if (!result || !result.q63) {
      return res.status(400).send({ code: 400, message: "Invalid data" });
    }

    // 获取当前价格，并保留四位小数
    let now_price = Number(result.q63);

    // 计算可以买的黄金克数，并保留4位小数
    let gram = (price / now_price).toFixed(4);
    gram = Number(gram);  // 转换为数字

    res.send({
      code: 200,
      data: gram
    });
  } catch (error) {
    console.error('Error in /get_gram:', error);
    res.status(500).send({ code: 500, message: "Server error" });
  }
})
// 添加年数据
router.post('/add_year', async (req, res) => {
  let form = req.body
  await YearQuoteModel.insertMany(form)
  res.send({
    code: 200,
    msg: 'success'
  })
})

// 在quote中筛选出日期最新的一条
// router.get('/get_nowdata', async (req, res) => {
//   let quoteResult = await Quote.findOne()
//   res.send({
//     code: 200,
//     data: quoteResult
//   })
// })
// 清空quote
// router.post('/clear_quote', async (req, res) => {
//   await Quote.deleteMany()
//   res.send({
//     code: 200,
//     msg: 'success'
//   })
// })
// 清空history
// router.post('/clear_history', async (req, res) => {
//   await HistoryFund.deleteMany()
//   res.send({
//     code: 200,
//     msg: 'success'
//   })
// })
// 清空月数据
// router.post('/clear_month', async (req, res) => {
//   await MonthQuoteModel.deleteMany()
//   res.send({
//     code: 200,
//     msg: 'success'
//   })
// })
// 清空周数据
// router.post('/clear_week', async (req, res) => {
//   await WeekQuoteModel.deleteMany()
//   res.send({
//     code: 200,
//     msg: 'success'
//   })
// })

// router.get('/get_newprice', async (req, res) => {
//   try {
//     // 查询数据库中所有的记录
//     const quotes = await Quote.find();
//     console.log(quotes, '000');
//     // 如果只有一条数据，直接返回
//     if (quotes.length == 1) {
//       console.log(quotes[0], '111');
//       return res.send({
//         code: 200,
//         data: quotes[0]
//       });
//     }
//     // 如果有多条数据，按日期筛选出最新的一条
//     const latestQuote = quotes.sort((a, b) => {
//       // q59是字符串，按照日期的字典顺序进行排序
//       return new Date(b.q59) - new Date(a.q59); // 按照日期降序排序
//     })[0]; // 获取最新的记录
//     res.send({
//       code: 200,
//       data: latestQuote
//     });
//   } catch (error) {
//     res.status(500).send({
//       code: 500,
//       message: error.message
//     });
//   }
// });
// 获取实时金价
// async function getGoldPrice() {
//   try {
//     const database = client.db('el');
//     const collection = database.collection('quotes');
//     const query = { q63: { $exists: true } };
//     const projection = { q63: 1, _id: 0 };
//     const doc = await collection.findOne(query, { projection }); // 获取一条记录即可
//     if (doc && doc.q63) {
//       const q63Value = parseFloat(doc.q63);
//       console.log(`实时金价: ${q63Value}`);
//       return q63Value;
//     }
//     throw new Error('未找到实时金价');
//   } catch (err) {
//     console.error('获取金价出错:', err);
//     throw err;
//   }
// }
// //获取收盘金价，用于定时任务存储到数据库
// async function getEndPrice() {
//   try {
//     const database = client.db('el');
//     const collection = database.collection('quotes');
//     const query = { q2: { $exists: true } };
//     const projection = { q2: 1, _id: 0 };
//     const doc = await collection.findOne(query, { projection }); // 获取一条记录即可
//     if (doc && doc.q2) {
//       const q2Value = parseFloat(doc.q2);
//       console.log(`实时金价: ${q2Value}`);
//       return q2Value;
//     }
//     throw new Error('未找到实时金价');
//   } catch (err) {
//     console.error('获取金价出错:', err);
//     throw err;
//   }
// }
// // 计算克数
// function calculateGrams(money, price) {
//   if (price <= 0) {
//     throw new Error('Invalid price');
//   }
//   return money / price;
// }
// //判断是否下午3点之后
// function isAfter3PM() {
//   const now = new Date();
//   const hours = now.getHours();
//   return hours >= 15;
// }
// //获取金价确认日期
// function getPriceConfirmationDate() {
//   const now = new Date();
//   const dayOfWeek = now.getDay();
//   //如果是下午3点之后
//   if (isAfter3PM()) {
//     if (dayOfWeek === 5) {
//       // 如果是星期五，则确认日期为下周一
//       now.setDate(now.getDate() + 3);
//     } else {
//       // 否则确认日期为下个工作日
//       now.setDate(now.getDate() + 1);
//     }
//   } else {
//     //如果是下午3点之前，则确认日期为当天20点
//     now.setDate(now.getDate());
//   }
//   now.setHours(20, 0, 0, 0)
//   return now;
// }
// //获取确认买入日期
// function getBuyConfirmationDate(priceConfirmationDate) {
//   const date = new Date(priceConfirmationDate);
//   if (date.getDay() === 5) {
//     //如果确认日期是星期五，则买入日期为下周一
//     date.setDate(date.getDate() + 3);
//   } else {
//     //否则买入日期为确认金价日期的下个工作日
//     date.setDate(date.getDate() + 1);
//   }
//   return date;
// }

// router.post('/buy', async (req, res) => {
//   try {
//     const { money, userId } = req.body;
//     if (!money || money <= 0) {
//       return res.status(400).json({ error: '金额无效' });
//     }

//     const priceConfirmationDate = getPriceConfirmationDate();
//     const buyConfirmationDate = getBuyConfirmationDate(priceConfirmationDate);
//     const goldPrice = await getGoldPrice();
//     const grams = calculateGrams(money, goldPrice);

//     await tradeModel.insertOne({
//       userId,
//       transactionAmount: money,
//       pricePerGram: goldPrice,
//       goldAmount: grams,
//       priceConfirmationDate,
//       buyConfirmationDate,
//       createdAt: new Date(),
//       status: 'pending'
//     });

//     res.status(200).json({
//       message: '购买成功',
//       money,
//       goldPrice,
//       grams,
//     });
//   } catch (err) {
//     console.error('处理购买请求出错:', err);
//     res.status(500).json({ error: '服务器内部错误' });
//   }
// });
// //定时任务，自动更新交易状态,从pending到confirmed确认金价,交易日20:45执行
// cron.schedule('31 21 * * 1-5', async () => {
//   try {
//     const currentDate = new Date();
//     //查询所有状态为pending的交易记录
//     const pendingTrades = await tradeModel.find({ status: 'pending' });
//     for (const trade of pendingTrades) {
//       const priceConfirmationDate = new Date(trade.priceConfirmationDate);
//       //如果当前日期>=确认买入日期，更新状态并生成持仓记录
//       const goldPrice = await getEndPrice();

//       const grams = calculateGrams(trade.pricePerGram, goldPrice); // 计算克数
//       if (currentDate >= priceConfirmationDate) {
//         trade.status = 'confirmed';//更新状态为confirmed，确认金价
//         trade.goldAmount = grams
//         await trade.save();
//       }
//     }
//   } catch (err) {
//     console.error('定时任务出错:', err);
//   }
// })
// //定时任务，自动更新交易状态，从confirmed到completed完成交易，并生成持仓表
// cron.schedule('48 10 * * 1-6', async () => {
//   try {
//     const currentDate = new Date();
//     // 查询所有状态为 confirmed 的交易记录
//     const confirmedTrades = await tradeModel.find({ status: 'confirmed' });
//     for (const trade of confirmedTrades) {
//       const buyConfirmationDate = new Date(trade.buyConfirmationDate);
//       // 如果当前日期 >= 确认买入日期，更新状态并生成持仓记录
//       if (currentDate >= buyConfirmationDate) {
//         trade.status = 'completed'; // 更新状态为 completed，完成交易
//         await trade.save();

//         // 查找用户是否已经存在持仓记录
//         const existingPosition = await positionModel.findOne({ userId: trade.userId });
//         if (existingPosition) {
//           // 如果存在持仓记录，累加黄金克数和总金额
//           existingPosition.goldAmount += trade.goldAmount;
//           existingPosition.totalAmount += trade.transactionAmount;
//           existingPosition.buyPrice = trade.pricePerGram; // 更新买入价
//           existingPosition.updatedAt = new Date();
//           await existingPosition.save();
//           console.log(`更新用户 ${trade.userId} 的持仓记录`);
//         } else {
//           // 如果不存在持仓记录，创建新的持仓记录
//           await positionModel.create({
//             userId: trade.userId,
//             goldAmount: trade.goldAmount,
//             buyPrice: trade.pricePerGram,
//             totalAmount: trade.transactionAmount,
//             createdAt: new Date(),
//           });
//           console.log(`创建用户 ${trade.userId} 的持仓记录`);
//         }
//       }
//     }
//     console.log('定时任务执行成功');
//   } catch (err) {
//     console.error('定时任务出错:', err);
//   }
// });
// //定时任务，自动更新收益表
// cron.schedule('58 10 * * 1-6', async () => {
//   try {
//     const position = await positionModel.find();
//     //获取昨天收盘价
//     const previousGoldPrice = await getPreviousGoldPrice();
//     //获取今天收盘价
//     const currentGoldPrice = await getTodayGoldPrice();
//     for (const pos of position) {
//       //当日收益金额
//       const earnings = (currentGoldPrice - previousGoldPrice) * pos.goldAmount;
//       //当日时间
//       const date = new Date();
//       //持有收益
//       const totalEarnings = (currentGoldPrice - pos.buyPrice) * pos.goldAmount;
//       //持有收益率
//       const totalRate = ((currentGoldPrice - pos.buyPrice) / pos.buyPrice) * 100;
//       await profitModel.updateOne({
//         userId: pos.userId,
//         positionId: pos._id
//       }, {
//         $push: {
//           dailyEarnings: [{
//             earnings: earnings,
//             date: date,
//           }],
//         },
//         $set: {
//           totalEarnings: totalEarnings,
//           totalRate: totalRate,
//         }
//       }, {
//         upsert: true,//如果记录不存在则插入
//       })
//     }
//     console.log('定时任务执行成功');

//   } catch (err) {
//     console.error('定时任务出错:', err);
//   }
// })


// //定时任务:存储每日收盘价---19:45
// cron.schedule('27 19 * * 1-5', async () => {
//   try {
//     const currentDate = new Date();
//     const goldPrice = await getEndPrice();
//     await goldHerstoryModel.updateOne(
//       {
//         date: currentDate.toISOString().split('T')[0],
//         price: goldPrice,
//       }, {
//       upsert: true,// 如果当日记录不存在，则插入；否则更新
//     }
//     );
//     console.log(`收盘价已存储: 日期 ${currentDate.toISOString().split('T')[0]}, 金价 ${goldPrice}`);
//   } catch (err) {
//     console.error('存储每日收盘价失败:', err);
//   }
// })
// //查询今天收盘价
// async function getTodayGoldPrice() {
//   try {
//     const today = new Date();

//     const todayPriceRecord = await goldHerstoryModel.findOne({
//       date: today.toISOString().split('T')[0],
//     });

//     if (todayPriceRecord && todayPriceRecord.price) {
//       return todayPriceRecord.price;
//     }
//     throw new Error('未找到今日金价');
//   } catch (err) {
//     console.error('获取今日金价失败:', err);
//     throw err;
//   }
// }
// //查询昨日收盘价
// async function getPreviousGoldPrice() {
//   try {
//     const yesterday = new Date();
//     yesterday.setDate(yesterday.getDate() - 1); // 昨天的日期

//     const previousPriceRecord = await goldHerstoryModel.findOne({
//       date: yesterday.toISOString().split('T')[0],
//     });

//     if (previousPriceRecord && previousPriceRecord.price) {
//       return previousPriceRecord.price;
//     }
//     throw new Error('未找到昨日金价');
//   } catch (err) {

//     console.error('获取昨日金价失败:', err);
//     throw err;
//   }
// }






// /* 支付 */
// const AlipaySDK = require('alipay-sdk').default;
// const AlipayFormData = require('alipay-sdk/lib/form').default;
// const alipaySdk = new AlipaySDK({
//   appId: '9021000142622638',
//   privateKey: 'MIIEowIBAAKCAQEAqYEXrapi3zsiH9RJnDyfAmd5Q2b6ZKDk3m8kEfu0s0c049Iyyr+VCqpAtNMsizEEx/rEiWbnRJlUx/fyrXImsKIA9ynCOMRmFP+VBANW8HBXM9OkCaKZVdsUyo+8/pUC/Q05mHSTj5FBNJkBy8SICIpLMCxLULsbbnAZbMx+qsD6R+QCOL7lVlSBD+6GFwv4NkKJom1Ez9HA9/LXE26qOWbGqcGzMrNxmezrVVZcwgWkbALrpmF2I8nQpT1TqW3XHGvHolO0jTgNoiNcsfxPElApE2NzgH/q+nuqsb9XYS62bMMSLieRU52fHfvnNrqkKsUzAJtPIgsONZHjWbVzKQIDAQABAoIBAQCj1w7/I2nMYokagQThysrb9Q6GcxxmdgqjYoRYCZdhjtt1trC3vzUeCPDgmBo/NJNthVvBgEDc0uTbITRmKKdzJjSOs8NzQYt2kpEEPwIjCEOR6eluEsfp8AiJvyQsY/ZuiQD59vzG0d1YLOlKf94JezswBjCKiUD7n8lDm+p3utW1ajo5X2H12GW636DsPz3lwfGIevZnZFh3gJkaPRipO/kj4dUFXSt09qXt37AJHhZAyPpQlqyzAegSZ81CrDS3k9Hh8rGkOVWE6EFrofx6nLafKQeoLJhlaDhLiG1/3vvp3fF/ni9KikvcygbqTzWBYLqRLOavwnXmXT48TQOxAoGBAPebMdq9qovJr1yAVGA5p8o/ac+5fVvL4hopVuD5XVNiq8/2fWGjk37RkcmIAAEz8G5EuSsqc9L9et7WqpECWgGQEho/KCSpWd+NcY+awCx5DvjM31iB67gyCEDi4KD+cIddblvo3FCsM4vuZohbO4OT22JklAqfy+dNCIzUWFLdAoGBAK9AGqyRe0yC7rxCeUgIsD0wBMAPF6wg9AVO0SyBbO4c6W+0FVPYewGTugEkjYApSjskD/AG4+FvNbPj0pW8iNert1fX72sFs4FwOa+v7FUclPI8JcvB1Yfa4WJyKkqc5wJdTIsONY0vFIldAeQWYYKFuqRMOWlrMeTiJY64Xf69AoGAT1sB42UeH6cH+NF4OU7BI+Sm+NguARma4V+WZIwHCQ56mjAZhw1x3Bc2biyUM859pBmKbvcwH9L1ai3KhKcISa/u3VKYfwd3sloWpzulk5tI3RxsCGW7MlF2q7UK4Q4q6ndbQ0GiOoi2DIbffZwfus/MZABwIeeM5hieQORdWlECgYAOkX2mKtHdImVGMSBz5IUCESPT8208WeDvMAYjdP7hLHYbWxUKy0wubWFhBvDcXpJVKEJK6ce3zc7hDWdMG0gk5ZlwK/szIl4xvGqPOEilKqMXH/jkX1Co4oEp9eOeIDzz7V2Xka7R9b/3S0wE8fdZKlTBo7SCFu8m38XPf3QQ4QKBgCy1kPo3IAF0qOnuQ2dKV+1LzZHBeC222EmcejOf7yoRmZtQKX54ayt0g6HSK1dL305JvCblbMp03AYtoRB8qI6/PKC1UrWtOnyRaldSKzO/Sqws7FvaIPCKphWccaGY84XvQw/v+eH5e8Mdk5xMvUWMT1oUFut3euPAKCLhKkQ2',
//   alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjGy8tEICYCxIg4Dd4/aLLbkHBkQ5J4Se0coDLbcMt/CeNkNYAmft7GTQWgZntRmk20C6NZlXisOLEfGOhrKvbaxHX2N3cw3sosRWU9D7Uo0ImZVhGt/f9aSv84cgx94vnJi15tUqE4DTN8ZNS1tOmFL/CutED5PRtDIHigPiRKPNDAxZIwwT3frdHcivD8f41bRpLwL48txdJxT5WgteEUUsjVLV8Onz+yj6JtSt3j/rRKM2jx40EcF/n/zOj6ntfgagsUoffk0dgQYq5SFvcYgAZ5E3eHIAeQsRyL8ufJnYEstZPlxQj4gG/hSnX07rWU5wYpCrazqljDBqUTrHdwIDAQAB',
//   gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do', // 沙箱环境
//   charset: 'utf-8',
//   signType: 'RSA2',
// });



// 韩博洋代码👇
// 添加 TransactionChoice 数据
router.post('/hhhh', async function (req, res, next) {
  const ratios = await RealTimeRatio.find();
  if (ratios.length === 0) {
    console.log('No RealTimeRatio data found, insert data first.');
    return;
  }
  const transactions = [
    {
      userid: '6746f69f32c730833561d694',
      choiceType: 'bull',
      date: '2024-12-01',
      realTimeRatioId: ratios[0]._id,
    },
    {
      userid: '6746f69f32c730833561d694',
      choiceType: 'bear',
      date: '2024-12-02',
      realTimeRatioId: ratios[1]._id,
    },
    {
      userid: '6746f69f32c730833561d694',
      choiceType: 'bull',
      date: '2024-12-03',
      realTimeRatioId: ratios[2]._id,
    },
    {
      userid: '6746f69f32c730833561d694',
      choiceType: 'bear',
      date: '2024-12-04',
      realTimeRatioId: ratios[3]._id,
    },
  ];
  try {
    await TransactionChoice.insertMany(transactions);
    res.status(200).json({ message: 'Transaction choices added successfully.' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 添加 RealTimeRatio 数据
router.post('/hhhb', async function (req, res, next) {
  const ratios = [
    { date: '2024-12-01', bullRatio: 55, bearRatio: 45 },
    { date: '2024-12-02', bullRatio: 60, bearRatio: 40 },
    { date: '2024-12-03', bullRatio: 50, bearRatio: 50 },
    { date: '2024-12-04', bullRatio: 65, bearRatio: 35 },
  ];
  try {
    await RealTimeRatio.insertMany(ratios);
    res.status(200).json({ message: 'RealTimeRatios added successfully.' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取 TransactionChoice 和 RealTimeRatio 数据
router.get('/data', async (req, res) => {
  try {
    // 获取所有 TransactionChoice 数据并关联 RealTimeRatio 数据
    const transactions = await TransactionChoice.find().populate('realTimeRatioId');

    // 检查是否存在数据
    if (!transactions || transactions.length === 0) {
      return res.status(404).json({ message: 'No transaction data found' });
    }

    // 打印并返回数据
    // console.log(transactions);
    res.send({
      status: 'success',
      data: transactions,
    });
  } catch (error) {
    // 捕获错误并返回错误信息
    console.error('Error fetching transaction data:', error.message);
    res.status(500).json({
      status: 'error',
      message: 'Failed to fetch transaction data',
      error: error.message,
    });
  }
});
router.post('/vote', async (req, res) => {
  const { userId, choiceType } = req.body; // 从请求中获取用户 ID 和选择类型
  const today = new Date().toISOString().split('T')[0]; // 获取当天日期
  try {
    // 1. 检查用户是否已在当天投票
    const existingChoice = await TransactionChoice.findOne({ userId, date: today });
    if (existingChoice) {
      return res.status(400).json({ message: '用户今天已经投票，不能重复投票！' });
    }

    // 2. 获取当天的比例数据
    let realTimeRatio = await RealTimeRatio.findOne({ date: today });

    // 如果当天没有比例数据，则初始化一条记录
    if (!realTimeRatio) {
      realTimeRatio = new RealTimeRatio({ date: today });
      await realTimeRatio.save();
    }

    // 3. 插入用户投票记录
    const newChoice = new TransactionChoice({
      userId,
      choiceType,
      date: today,
      realTimeRatioId: realTimeRatio._id,
    });
    await newChoice.save();

    // 4. 更新当天的看涨和看跌比例
    const bullVotes = await TransactionChoice.countDocuments({ date: today, choiceType: 'bull' });
    const bearVotes = await TransactionChoice.countDocuments({ date: today, choiceType: 'bear' });
    const totalVotes = bullVotes + bearVotes;

    realTimeRatio.bullRatio = ((bullVotes / totalVotes) * 100).toFixed(2);
    realTimeRatio.bearRatio = ((bearVotes / totalVotes) * 100).toFixed(2);
    realTimeRatio.updateTime = Date.now();
    await realTimeRatio.save();

    // 返回成功响应
    res.status(200).json({
      message: '投票成功！',
      data: {
        bullRatio: realTimeRatio.bullRatio,
        bearRatio: realTimeRatio.bearRatio,
      },
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误，请稍后再试！' });
  }
  // res.send({
  // 	code:200,
  // 	msg:'操作成功'
  // })
});
// 获取新闻数据
router.get('/news', async (req, res) => {
  let { size } = req.query
  try {
    // 发起 API 请求
    const response = await axios.get(`https://apis.tianapi.com/caijing/index?key=32b983eb337dc2a6a6cede45ebaed0bb&num=${size}`);
    // 返回 API 的数据部分
    res.status(200).json(response.data);
    console.log(response.data);
  } catch (error) {
    // 打印详细的错误信息，便于调试
    console.error('Error fetching data from API:', error.message);
    if (error.response) {
      console.error('Response error:', error.response.data);
    }

    // 返回 500 错误
    res.status(500).json({ error: 'Failed to fetch data' });
  }
});

// 用户信息获取  设置相关
router.get('/info_user', async (req, res) => {
  console.log(req.query, 'ggggggggggg');

  try {


    // 发起 API 请求
    let response = await userModel.findById(req.query.id)
    if (response) {
      res.send({
        code: 200,
        data: response
      })
    } else {
      res.send({
        code: 404,
        data: []
      })
    }
  } catch (error) {
    // 打印详细的错误信息，便于调试
    console.error('Error fetching data from API:', error.message);
    if (error.response) {
      console.error('Response error:', error.response.data);
    }
    // 返回 500 错误
    res.status(500).json({ error: 'Failed to fetch data' });
  }
});
// 用户信息修改 设置相关
router.post('/update_user_image', async (req, res) => {

  try {
    // 发起 API 请求
    let response = await userModel.findByIdAndUpdate(req.body.id, { avater: req.body.avatar })
    if (response) {
      res.send({
        code: 200,
        msg: '修改成功'
      })
      console.log('修改成功');

    } else {
      res.send({
        code: 404,
        data: []
      })
    }
  } catch (error) {
    // 打印详细的错误信息，便于调试
    console.error('Error fetching data from API:', error.message);
    if (error.response) {
      console.error('Response error:', error.response.data);
    }
    // 返回 500 错误
    res.status(500).json({ error: 'Failed to fetch data' });
  }
});
// 韩博洋代码👆





// 启动时连接 MongoDB
(async () => {
  try {
    await client.connect();
    console.log('MongoDB 已连接');
  } catch (err) {
    console.error('MongoDB 连接失败:', err);
  }
})();

//---------------------登录----------------------------------------

const setAccessToken = (user = {}) => {
  return jsonwebtoken.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '2h' })
}

const setRefreshToken = (user = {}) => {
  return 'Bearer ' + jsonwebtoken.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '72h' })
}




//是否登录成功
const login_c = async (user, res, msg) => {
  if (user) {
    let token = setAccessToken({ user: user._id })
    let reftoken = setRefreshToken({ user: user._id })
    add_accessToken([token, user._id])
    await tokenModel.deleteOne({ uid: user._id })
    await tokenModel.create({ token: reftoken, uid: user._id })
    res.send({
      code: 200,
      msg: "登陆成功",
      data: { userId: user._id, isreal: user.id_card ? true : false },
      token: token
    })
  } else {
    res.send({
      code: 201,
      msg: "该用户不存在"
    })
  }
}

//短信验证码
let { send, yz } = require('../token/code');
router.post("/sendCode", (req, res) => {
  let { phone } = req.body
  send(phone).then(() => {
    res.send({ code: 200, msg: "发送成功" })
  }).catch((err) => {
    res.send({ code: 201, msg: "发送失败" })
  })
})

//手机号验证码登录
router.post("/yzm_login", async (req, res) => {
  let { phone, yzm } = req.body
  let user = await userModel.findOne({ phone })
  let { code, msg } = yz(phone, yzm)
  if (code == 200) {
    login_c(user, res)
  } else {
    res.send({ code: 201, msg: msg })
  }
})

//密码登录
router.post("/login", async (req, res) => {
  let { phone, password } = req.body
  let user = await userModel.findOne({ phone })
  if (!user) {
    res.send({ code: 201, msg: "该手机号未注册" })
  } else {
    if (user.password == password) {
      login_c(user, res)
    } else {
      res.send({ code: 201, msg: "密码错误" })
    }
  }
})

//通过找到长token，刷新短token
router.post("/token", async (req, res) => {
  let { id } = req.body
  let use = await tokenModel.findOne({ uid: id })
  console.log(use, 'uuuussseeetoken')
  if (use) {
    let token = setAccessToken({ user: use._id })
    add_accessToken([token, use.uid])
    res.send({ code: 200, msg: '成功刷新', token })
  } else {
    res.send({ code: 201, msg: "token以到期,请重新登录" })
  }
})

//注册
router.post("/register", async (req, res) => {
  let { phone, password, yzm } = req.body
  let { code, msg } = yz(phone, yzm)
  if (code == 200) {
    if (phone && password) {
      let user = await userModel.findOne({ phone })
      if (user) {
        res.send({ code: 201, msg: "该手机号以注册" })
      } else {
        userModel.create({ phone, password })
        res.send({ code: 200, msg: "注册成功" })
      }
    } else {
      res.send({ code: 201, msg: "手机号和密码都不能为空" })
    }
  } else {
    res.send({ code: 201, msg: "验证码错误" })
  }

})
//密码重置
router.post("/resetpassword", async (req, res) => {
  let { phone, password, yzm } = req.body
  let userr = await userModel.find({ phone: phone })
  let { code, msg } = yz(phone, yzm)
  if (code == 200) {
    if (userr) {
      await userModel.updateOne({ phone }, { password })
      res.send({
        code: 200,
        msg: '密码重置成功'
      })
    } else {
      res.send({
        code: 201,
        msg: "未找到该用户"
      })
    }
  } else {
    res.send({ code: 201, msg: msg })
  }
})

//退出
router.post("/tui_login", async (req, res) => {
  let { id } = req.body
  console.log(id, 'tttuuuiiiggguuuiii')
  await tokenModel.deleteOne({ uid: id })
  delete_access(id)
  res.send({ code: 200, msg: "退出成功" })
})

//注销,会将该用户的短token，长token全部删除
router.post("/zhuxiao", async (req, res) => {
  let { id } = req.body
  await userModel.deleteOne({ _id: id })
  await tokenModel.deleteOne({ uid: id })
  delete_access(id)
  res.send({ code: 200, msg: "注销成功" })
})

//上传身份证并识别
let muti = require("multiparty")
let fs = require("fs")
router.post("/sfrz", async (req, res) => {
  let form = new muti.Form()
  form.uploadDir = 'public/images'
  form.parse(req, async (err, fields, files) => {

    if (err) return
    let q = await main(files.image[0].path)
    if (q) {
      res.send({ code: 200, data: q })
    } else {
      res.send({ code: 201, msg: "身份证识别失败" })
    }
  })
})

//修改用户信息
router.post("/update_user", async (req, res) => {
  let { id } = req.body
  await userModel.updateOne({ _id: id }, req.body)
  res.send({
    code: 200
  })
})

router.post("/mydata", async (req, res) => {
  let { id } = req.body
  let user = await userModel.findById({ _id: id })
  if (user) {
    res.send({ code: 200, data: user })
  } else {
    res.send({ code: 201, msg: "失败" })
  }
})

//-----------------商城-----------------------------
//获取实时金价和商品价格
async function updateProductPricesWithGoldPrice() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');
    const database = client.db('el');
    const quotesCollection = database.collection('quotes');
    const productsCollection = database.collection('product');
    const quoteDoc = await quotesCollection.findOne({ q63: { $exists: true } }, { projection: { q63: 1, _id: 0 } });
    if (!quoteDoc) {
      throw new Error('No gold price found');
    }
    const goldPrice = parseFloat(quoteDoc.q63).toFixed(1);
    console.log('Gold price:', goldPrice);
    const products = await productsCollection.find().toArray();
    for (const product of products) {
      product.price = product.grams * parseFloat(goldPrice).toFixed(1);
      await productsCollection.updateOne({ _id: product._id }, { $set: { price: product.price } });
    }
    console.log('Product prices updated successfully.');
  } catch (err) {
    console.error('Error updating product prices:', err);
  } finally {
    // await client.close();
    console.log('MongoDB connection closed');
  }
}

// // 调用函数
updateProductPricesWithGoldPrice();


//添加商品
router.post('/add_product', async (req, res) => {
  const { name, price, grams, images, sales, description, collection, num, purity } = req.body
  const product = new ProductModel({
    name, price, grams, images, sales, description, collection, num, purity
  })
  await product.save()
  res.send('添加成功')
})


// 查看全部商品
router.get('/product', async (req, res) => {
  const { page, size } = req.query;
  const skip = (page - 1) * size;
  const products = await ProductModel.find().skip(skip).limit(size);
  const total = await ProductModel.countDocuments();
  res.send({
    code: 200,
    data: products,
    total
  });
});


//查看商品详情
router.get('/product_detail', async (req, res) => {
  const id = req.query.id
  console.log(id, 88888888);
  const product = await ProductModel.findById(id)
  res.send({
    code: 200,
    data: product
  })
})


//商品收藏
router.post('/product_like', async (req, res) => {
  const { id, like } = req.body;
  console.log(id, like);
  try {
    // 使用findByIdAndUpdate来更新文档，new: true 确保返回更新后的文档
    const updatedProduct = await ProductModel.findByIdAndUpdate(
      id, // 查询条件，根据id查找文档
      { $set: { like: like } }, // 更新内容，$set操作符用于更新字段
      { new: true } // 返回更新后的文档
    );
    console.log(updatedProduct);
    res.send({
      code: 200,
      data: updatedProduct
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({ code: 500, message: 'Internal Server Error' });
  }
});

// 查找收藏商品
router.get('/product_like', async (req, res) => {
  try {
    const product = await ProductModel.find({ like: true });
    res.send({
      code: 200,
      data: product
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({ code: 500, message: 'Internal Server Error' });
  }
});


//支付商城订单
router.post('/shang_pay', async (req, res) => {
  //订单号
  const id = req.body.id
  const iddata = await ProductModel.findById(id)
  console.log(iddata, 999888774455666);
  const proname = iddata.name
  const grams = iddata.grams
  const images = iddata.images
  const priceone = iddata.price
  const orderId = 'ORDER' + Date.now();
  //商品总价
  let price = req.body.price
  //商品名称
  let name = req.body.name
  let userId = req.body.userId
  let addressId = req.body.addressId
  let num = req.body.num
  const addressData = await AddressModel.findById(addressId)
  if (!addressData) {
    return res.status(400).send({ code: 400, message: 'Address not found' });
  }
  const newOrder = {
    cid: userId,
    pid: id,
    num: num,
    price: price,
    status: 'Paid',
    address: addressId,
    orderId: orderId,
    createdAt: new Date(),
    proname: proname,
    grams: grams,
    images: images,
    priceone: priceone,
  }
  try {
    //开始对接支付宝API
    const formData = new AlipayFormData()
    //调用setMethod并传入get,会返回可以跳转到支付页面的url
    formData.setMethod('get')
    //支付时信息
    const bizContent = {
      out_trade_no: orderId, //订单号
      // FAST_INSTANT_TRADE_PAY
      // QUICK_WAP_WAY
      product_code: "QUICK_WAP_WAY",
      total_amount: price, //总价格
      subject: name, //商品名称
      body: "商品详情", //商品描述
    }
    console.log(bizContent, 'bizContent');

    formData.addField("bizContent", bizContent)//业务参数
    //支付成功或失败的返回链接（前端页面）
    formData.addField("returnUrl", "http://localhost:8081/tabs/shouye")
    // formData.addField("notifyUrl", "https://192.168.190.176:3000/alipay_callback");  // 支付宝通知支付结果的回调地址


    const createOrder = await OrderModel.create(newOrder)
    console.log(createOrder, 123456789);
    console.log(formData, 1234567891111111111);

    const result = alipaySdk.exec(
      // "alipay.trade.page.pay",
      "alipay.trade.wap.pay",
      {},
      { formData: formData }
    ).catch(error => console.error('caught error!', error));
    //支付宝对接成功 支付宝返回的数据
    console.log(result, 123);

    result.then(async (resp) => {
      res.send({
        data: {
          code: 200,
          success: true,
          msg: '支付中',
          paymentUrl: resp,
          qrCodeUrl: `/qrcode.png`,
          order: createOrder
        }
      })
    })
  } catch (error) {
    res.send({
      data: {
        code: 500,
        success: false,
        msg: '支付失败',
        error: error
      }
    })
  }
})

// 支付宝支付完成后的回调接口
// router.post('/alipay_callback', async (req, res) => {
//   console.log('支付宝支付完成后的回调接口');
//   const params = req.body
//   console.log(params, 8888);
//   const isValid = await alipaySdk.checkNotifySign(params)
//   if (!isValid) {
//     return res.send({
//       data: {
//         code: 500,
//         success: false,
//         msg: '签名验证失败'
//       }
//     })
//   }
//   if (params.trade_status === 'TRADE_SUCCESS') {
//     // 更新订单状态
//     const orderId = params.out_trade_no
//     const order = await OrderModel.findOne({ orderId })
//     if (!order) {
//       return res.send({
//         data: {
//           code: 500,
//           success: false,
//           msg: '订单不存在'
//         }
//       })
//     }
//     if (order.status == 'Paid') {
//       return res.send({
//         data: {
//           code: 200,
//           success: true,
//           msg: '支付成功'
//         }
//       })
//     }
//     order.status = 'Paid'
//     order.paidAt = new Date()
//     await order.save()
//     console.log(order, 8888);
//     return res.send({
//       data: {
//         code: 200,
//         success: true,
//         msg: '支付成功'
//       }
//     })
//   } else {
//     return res.send({
//       data: {
//         code: 500,
//         success: false,
//         msg: '支付失败'
//       }
//     })
//   }

// })


//查看已支付的订单

router.get('/getPaidOrder', async (req, res) => {
  const { userId } = req.query
  const orderData = await OrderModel.find({ cid: userId })
  res.send({
    data: {
      code: 200,
      success: true,
      msg: '获取成功',
      data: orderData
    }
  })
})


//添加地址
router.post('/addAddress', async (req, res) => {
  const { name, phone, area, details, userId, isDefault } = req.body
  console.log(req.body, 8888);

  const addressData = await AddressModel.create({ name, phone, area, details, cid: userId, isDefault })
  res.send({
    data: {
      code: 200,
      success: true,
      msg: '添加成功',
      data: addressData
    }
  })
})

//查看地址
router.get('/address', async (req, res) => {
  const { userId } = req.query
  console.log(userId, 9999);
  const addressData = await AddressModel.find({ cid: userId })
  res.send({
    data: {
      code: 200,
      success: true,
      msg: '查询成功',
      data: addressData
    }
  })
})

//修改默认地址
router.get('/address/update', async (req, res) => {
  const { addressId } = req.query
  console.log(req.query, 8888);
  const addressData = await AddressModel.find({ _id: addressId })
  if (addressData[0].isDefault == true) {
    await AddressModel.updateMany({ cid: addressData[0].cid }, { $set: { isDefault: false } })
  } else {
    await AddressModel.updateMany({ cid: addressData[0].cid }, { $set: { isDefault: false } })
    await AddressModel.updateOne({ _id: addressId }, { $set: { isDefault: true } })
  }
  res.send({
    data: {
      code: 200,
      success: true,
      msg: '修改成功',
      data: addressData
    }
  })
})

//删除地址
router.get('/address/delete', async (req, res) => {
  const { addressId } = req.query
  const addressData = await AddressModel.deleteOne({ _id: addressId })
  res.send({
    data: {
      code: 200,
      success: true,
      msg: '删除成功',
      data: addressData
    }
  })
})

//修改地址
router.get('/upaddress', async (req, res) => {
  const { addressId, name, phone, area, details } = req.query
  const addressData = await AddressModel.find({ _id: addressId })
  addressData[0].name = name
  addressData[0].phone = phone
  addressData[0].area = area
  addressData[0].details = details
  await addressData[0].save()
  res.send({
    data: {
      code: 200,
      success: true,
      msg: '修改成功',
      data: addressData
    }
  })

})


//改变商品的状态
router.get('/change', async (req, res) => {
  const { id } = req.query
  const orderData = await OrderModel.find({ _id: id })
  orderData[0].status = 'Finished'
  await orderData[0].save()
  res.send({
    data: {
      code: 200,
      success: true,
      msg: '修改成功',
      data: orderData
    }
  })
})





module.exports = router;
